<template>
  <div class="equipment-maintenance">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button type="primary" @click="showAddDialog">
          <i class="el-icon-plus"></i>
          新增设备维修
        </el-button>
      </div>
      <div class="header-right">
        <div class="search-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入设备名称/设备编码"
            clearable
            @keyup.enter="handleSearch"
            style="width: 300px; margin-right: 10px;"
          >
            <template #append>
              <el-button @click="handleSearch">
                <i class="el-icon-search"></i>
              </el-button>
            </template>
          </el-input>
          <el-button @click="showFilterDialog">
            <i class="el-icon-filter"></i>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >

        <el-table-column prop="equipmentName" label="设备名称" width="80" align="center" />
        <el-table-column prop="equipmentCode" label="设备编码" width="100" align="center" />
        <el-table-column prop="maintenanceItem" label="维修项目" width="100" align="center" />
        <el-table-column prop="maintenancePerson" label="维修人" width="100" align="center" />
        <el-table-column prop="maintenanceTime" label="维修时间" width="100" align="center">
          <template #default="{ row }">
            {{ formatDate(row.maintenanceTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="maintenanceHours" label="维修工时" width="100" align="center" />
        <el-table-column prop="maintenanceCost" label="维修费用" width="100" align="center">
          <template #default="{ row }">
            {{ row.maintenanceCost ? '¥' + row.maintenanceCost : '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="faultDescription" label="故障详情" width="150" align="center">
          <template #default="{ row }">
            {{ row.faultDescription || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="handlingSituation" label="处理情况" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.handlingSituation)">
              {{ getStatusText(row.handlingSituation) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleEdit(row)" style="color: #409EFF;">修改</el-button>
            <el-button type="text" @click="handleDelete(row)" style="color: #F56C6C;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="maintenanceForm"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="设备名称" prop="equipmentId">
          <el-select
            v-model="formData.equipmentId"
            placeholder="请选择设备"
            style="width: 100%"
            @change="handleEquipmentChange"
          >
            <el-option
              v-for="equipment in equipmentList"
              :key="equipment.equipmentId"
              :label="equipment.equipmentName"
              :value="equipment.equipmentId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备编码" prop="equipmentCode">
          <el-input v-model="formData.equipmentCode" disabled />
        </el-form-item>
        <el-form-item label="维修项目" prop="maintenanceItem">
          <el-input v-model="formData.maintenanceItem" placeholder="请输入维修项目" />
        </el-form-item>
        <el-form-item label="维修人" prop="maintenancePerson">
          <el-input v-model="formData.maintenancePerson" placeholder="请输入维修人" />
        </el-form-item>
        <el-form-item label="维修时间" prop="maintenanceTime">
          <el-date-picker
            v-model="formData.maintenanceTime"
            type="date"
            placeholder="选择维修时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="维修工时" prop="maintenanceHours">
          <el-input-number
            v-model="formData.maintenanceHours"
            :min="0"
            :precision="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="维修费用" prop="maintenanceCost">
          <el-input-number
            v-model="formData.maintenanceCost"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="故障详情" prop="faultDescription">
          <el-input
            v-model="formData.faultDescription"
            type="textarea"
            :rows="3"
            placeholder="请输入故障详情"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 筛选对话框 -->
    <el-dialog title="筛选条件" v-model="filterDialogVisible" width="400px">
      <el-form :model="filterForm" label-width="100px">
        <el-form-item label="设备名称">
          <el-input v-model="filterForm.equipmentName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="维修项目">
          <el-input v-model="filterForm.maintenanceItem" placeholder="请输入维修项目" />
        </el-form-item>
        <el-form-item label="维修人">
          <el-input v-model="filterForm.maintenancePerson" placeholder="请输入维修人" />
        </el-form-item>
        <el-form-item label="维修时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetFilter">重置</el-button>
          <el-button @click="filterDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleFilter">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'EquipmentMaintenance',
  data() {
    return {
      // 响应式数据
      loading: false,
      submitLoading: false,
      dialogVisible: false,
      filterDialogVisible: false,
      dialogTitle: '新增设备维修',
      isEdit: false,
      
      // 表格数据
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      searchKeyword: '',
      
      // 设备列表
      equipmentList: [],
      
      // 表单数据
      formData: {
        equipmentMaintenanceId: '',
        equipmentId: '',
        equipmentCode: '',
        equipmentName: '',
        maintenanceItem: '',
        maintenancePerson: '',
        maintenanceTime: '',
        maintenanceHours: 0,
        maintenanceCost: 0,
        faultDescription: ''
      },
      
      // 筛选表单
      filterForm: {
        equipmentName: '',
        maintenanceItem: '',
        maintenancePerson: '',
        dateRange: []
      },
      
      // 表单验证规则
      formRules: {
        equipmentId: [
          { required: true, message: '请选择设备', trigger: 'change' }
        ],
        maintenanceItem: [
          { required: true, message: '请输入维修项目', trigger: 'blur' }
        ],
        maintenancePerson: [
          { required: true, message: '请输入维修人', trigger: 'blur' }
        ],
        maintenanceTime: [
          { required: true, message: '请选择维修时间', trigger: 'change' }
        ]
      }
    }
  },
  
  mounted() {
    this.getEquipmentList()
    this.getMaintenanceRecordList()
  },
  
  methods: {
    // 获取设备列表
    async getEquipmentList() {
      try {
        const response = await request.get('/equipment/equipmentNames')
        if (response.code === 200) {
          this.equipmentList = response.data || []
        }
      } catch (error) {
        console.error('获取设备列表失败:', error)
      }
    },
    
    // 获取维修记录列表
    async getMaintenanceRecordList() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          keyword: this.searchKeyword
        }
        
        const response = await request.post('/equipmentMaintenance/page', params)
        if (response.code === 200) {
          this.tableData = response.data.records || []
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.data.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取维修记录失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getMaintenanceRecordList()
    },
    
    // 显示新增对话框
    showAddDialog() {
      this.dialogTitle = '新增设备维修'
      this.isEdit = false
      this.dialogVisible = true
      this.resetForm()
    },
    
    // 编辑
    handleEdit(row) {
      this.dialogTitle = '修改设备维修'
      this.isEdit = true
      this.dialogVisible = true
      
      // 填充表单数据
      Object.assign(this.formData, {
        equipmentMaintenanceId: row.equipmentMaintenanceId,
        equipmentId: row.equipmentId,
        equipmentCode: row.equipmentCode,
        equipmentName: row.equipmentName,
        maintenanceItem: row.maintenanceItem,
        maintenancePerson: row.maintenancePerson,
        maintenanceTime: row.maintenanceTime,
        maintenanceHours: row.maintenanceHours || 0,
        maintenanceCost: row.maintenanceCost || 0,
        faultDescription: row.faultDescription || ''
      })
    },
    
    // 删除
    async handleDelete(row) {
      try {
        await this.$confirm(
          `确定要删除设备"${row.equipmentName}"的维修记录吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await request.delete(`/equipmentMaintenance/delete/${row.equipmentMaintenanceId}`)
        if (response.code === 200) {
          this.$message.success('删除成功')
          this.getMaintenanceRecordList()
        } else {
          this.$message.error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },
    
    // 设备选择变化
    handleEquipmentChange(equipmentId) {
      const equipment = this.equipmentList.find(item => item.equipmentId === equipmentId)
      if (equipment) {
        this.formData.equipmentCode = equipment.equipmentCode
        this.formData.equipmentName = equipment.equipmentName
      }
    },
    
    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.maintenanceForm.validate()
        
        this.submitLoading = true
        
        const url = this.isEdit ? '/equipmentMaintenance/update' : '/equipmentMaintenance/add'
        const response = await request({
          url,
          method: this.isEdit ? 'put' : 'post',
          data: this.formData
        })
        
        if (response.code === 200) {
          this.$message.success(this.isEdit ? '修改成功' : '新增成功')
          this.dialogVisible = false
          this.getMaintenanceRecordList()
        } else {
          this.$message.error(response.data.message || '操作失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('操作失败')
      } finally {
        this.submitLoading = false
      }
    },
    
    // 重置表单
    resetForm() {
      Object.assign(this.formData, {
        equipmentMaintenanceId: '',
        equipmentId: '',
        equipmentCode: '',
        equipmentName: '',
        maintenanceItem: '',
        maintenancePerson: '',
        maintenanceTime: '',
        maintenanceHours: 0,
        maintenanceCost: 0,
        faultDescription: ''
      })
      if (this.$refs.maintenanceForm) {
        this.$refs.maintenanceForm.resetFields()
      }
    },
    
    // 显示筛选对话框
    showFilterDialog() {
      this.filterDialogVisible = true
    },
    
    // 筛选
    handleFilter() {
      // 这里可以根据筛选条件进行查询
      this.filterDialogVisible = false
      this.getMaintenanceRecordList()
    },
    
    // 重置筛选
    resetFilter() {
      Object.assign(this.filterForm, {
        equipmentName: '',
        maintenanceItem: '',
        maintenancePerson: '',
        dateRange: []
      })
    },
    
    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getMaintenanceRecordList()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.getMaintenanceRecordList()
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '--'
      return new Date(date).toLocaleDateString()
    },
    
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: 'info',
        1: 'success',
        2: 'warning',
        3: 'danger'
      }
      return statusMap[status] || 'info'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待处理',
        1: '已完成',
        2: '进行中',
        3: '已取消'
      }
      return statusMap[status] || '未知'
    }
  }
}
</script>

<style scoped>
.equipment-maintenance {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left .el-button {
  background: #409EFF;
  border-color: #409EFF;
  color: white;
  padding: 12px 24px;
  font-size: 14px;
}

.header-left .el-button:hover {
  background: #66b1ff;
  border-color: #66b1ff;
}

.search-bar {
  display: flex;
  align-items: center;
}

.search-bar .el-button {
  background: #409EFF;
  border-color: #409EFF;
  color: white;
  width: 40px;
  height: 40px;
  padding: 0;
}

.search-bar .el-button:hover {
  background: #66b1ff;
  border-color: #66b1ff;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-table {
  font-size: 14px;
}

.el-table th {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

.el-pagination {
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .header-right {
    width: 100%;
  }
  
  .search-bar {
    width: 100%;
  }
  
  .search-bar .el-input {
    width: 100% !important;
  }
}
</style>